/**
 * Created by admin on 2017/1/6.
 * 1. 单个的碰撞检测
 */

// 如果要横向判断碰撞的话，判断(x1-x2)的绝对值是否小于或者等于w1/2+w2/2，
// 如果是则横向则有碰撞。纵向判断是一样的，判断(y1-y2)的绝对值是否小于或等于h1/2+h2/2即可。

var BOX = document.getElementById('touch');

var bbody = {
  w: BOX.clientWidth,
  h: BOX.clientHeight,
  x: BOX.offsetLeft + BOX.clientWidth / 2,
  y: BOX.offsetTop + BOX.clientHeight / 2,
}

// 被碰撞物体
var Peng = document.getElementById('peng');

var pengbody = {
  w: Peng.clientWidth,
  h: Peng.clientHeight,
  x: Peng.offsetLeft + Peng.clientWidth / 2,
  y: Peng.offsetTop + Peng.clientHeight / 2,
}

/**
 * 碰撞检测
 * @param a
 * @param b
 * @returns {boolean}
 */
var testColl = function (a, b) {
  var coll = false;
  if ((Math.abs(a.x - b.x) <= (a.w / 2 + b.w / 2)) && (Math.abs(a.y - b.y) <= (a.h / 2 + b.h / 2))) {
    coll = true
  }
  return coll;
};

var move = false
var mousedown = function () {
  move = true
};
var mousemove = function (e) {
  if (!move) return;
  BOX.style.top = e.pageY - bbody.h / 2 + 'px';
  BOX.style.left = e.pageX - bbody.w / 2 + 'px';
  bbody.x = e.pageX;
  bbody.y = e.pageY;

  // testColl(bbody, pengbody)
  console.log(testColl(bbody, pengbody));
};
var mouseup = function () {
  move = false
  mousemove();
};


BOX.addEventListener('mousedown', mousedown);
BOX.addEventListener('mouseup', mouseup);
document.addEventListener('mousemove', mousemove);
